package com.ywd.materials.admin.exception;

import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.Map;

/**
 * @author lk
 */
@Data
@Accessors(chain = true)
public class R<T> implements Serializable {
    private long code;
    private T data;
    private String message;

    public R() {
    }

    public R(long code, String message) {
        this.code = code;
        this.message = message;
    }

    public R(long code, T data, String message) {
        this.code = code;
        this.data = data;
        this.message = message;
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, ApiErrorCode.SUCCESS);
    }

    public static <T> R<T> ok() {
        ApiErrorCode aec = ApiErrorCode.SUCCESS;

        return restResult(aec);
    }

    public static <T> R<T> error(T data) {
        ApiErrorCode aec = ApiErrorCode.FAILED;
        if (data instanceof Boolean && Boolean.FALSE.equals(data)) {
            aec = ApiErrorCode.FAILED;
        }
        return restResult(data, aec);
    }

    public static <T> R<T> error() {
        ApiErrorCode aec = ApiErrorCode.FAILED;
        return restResult(aec);
    }

    public static <T> R<T> error(ApiErrorCode aec) {
        return restResult(aec);
    }

    public static <T> R<T> failed(String msg) {
        return restResult(null, ApiErrorCode.FAILED.getCode(), msg);
    }

    public static <T> R<T> restResult(T data, IErrorCode errorCode) {
        return restResult(data, errorCode.getCode(), errorCode.getMsg());
    }

    public static <T> R<T> restResult(IErrorCode errorCode) {
        return restResult(errorCode.getCode(), errorCode.getMsg());
    }

    private static <T> R<T> restResult(T data, long code, String msg) {
        if (code == ApiErrorCode.FAILED.getCode()) {
            if (data instanceof Throwable) {
                // 处理异常类型
                msg = ((Throwable) data).getMessage();
            } else if (data instanceof Map) {
                // 处理Map类型（包括HashMap）
                Map<?, ?> map = (Map<?, ?>) data;
                Object errMsg = map.get("errMsg");
                if (errMsg != null) {
                    msg = errMsg.toString();
                } else {
                    msg = "操作失败，请查看返回数据";
                }
                Object errCode = map.get("errCode");
                //token过期未为特殊值
                if (errCode != null && errCode.equals("20004")) {
                    code = Long.parseLong("1");
                }
            } else if (data != null) {
                // 处理其他非空对象
                msg = data.toString();
            }
            return new R<>(code, msg);
        }
        return new R<>(code, data, msg);
    }

    private static <T> R<T> restResult(long code, String msg) {
        R<T> result = new R<>();
        result.setCode(code);
        result.setMessage(msg);
        return result;
    }
}